package org.j4me.deviceinfo.data;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Vector;

import org.dom4j.Element;

public class Model {
	Vector<Device> _devices = new Vector<Device>();
	private String _name;

	public Model(String model) {
		_name = model;
	}

	public Model(Brand b, Element elt) {
		_name = elt.attributeValue("name");
		Iterator it = elt.selectNodes("device").iterator();
		while (it.hasNext()) {
			Device device = new Device(b, this, (Element) it.next());
			addDevice(device);
		}
	}

	public Enumeration<Device> getDevices() {
		return _devices.elements();
	}

	public void addDevice(Device device) {
		Enumeration<Device> devices = getDevices();
		while (devices.hasMoreElements()) {
			Device current = (Device) devices.nextElement();
			if (device.equals(current)) {
				current.increment();
				return;
			}
		}
		_devices.add(device);
	}

	public String getName() {
		return _name;
	}

	public void addXmlNode(Element root) {
		Element model = root.addElement("model");
		model.addAttribute("name", _name);
		Enumeration<Device> devices = getDevices();
		while (devices.hasMoreElements()) {
			Device device = (Device) devices.nextElement();
			device.addXmlNode(model);
		}
	}

	public void merge(Model source) {
		_devices.addAll(source._devices);
	}

	public int getDeviceCount() {
		return _devices.size();
	}

	public int getHitCount() {
		int count = 0;
		Enumeration<Device> devices = getDevices();
		while (devices.hasMoreElements()) {
			count += devices.nextElement().getHits();
		}
		return count;
	}
}
